﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using MovieCollectionManager.DataModel;
using MovieCollectionManager.Util;

namespace MovieCollectionManager
{
    public partial class LoginForm : Form
    {
        private MainForm mainForm;
        public static string loggedUser;

        public LoginForm(MainForm main)
        {
            mainForm = main;
            ShowSplashScreen();
            InitializeComponent();
        }

        private static void ShowSplashScreen()
        {
            SplashScreenForm splashScreenForm = new SplashScreenForm();
            splashScreenForm.Show();
            splashScreenForm.Update();
            Thread.Sleep(2000);
            splashScreenForm.Close();
        }

        private void buttonQuit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void buttonOk_Click(object sender, EventArgs e)
        {
            bool isAdmin = false;
            using (var db = new MovieCollectionConteiner())
            {
                try
                {
                    User user = (from user1 in db.Users
                                 where user1.Name == textBoxUsername.Text
                                 select user1).First();

                    string inputPassword = Security.GenerateHash(textBoxPassword.Text);

                    if (!inputPassword.Equals(user.Password.ToString()))
                    {
                        MessageBox.Show("Senha incorreta!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        return;
                    }

                    loggedUser = user.Name;
                    isAdmin = user.IsAdmin;
                    textBoxPassword.Text = "";
                }
                catch (InvalidOperationException)
                {
                    MessageBox.Show("Usuário inexistente!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                catch (Exception)
                {
                    MessageBox.Show("Base de dados não existe. Crie antes de executar!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }

            Hide();
            ShowPendingLoansForm();
            CreateMainForm();
            AccessControlsVisibility(true);
            AdminControlsVisibility(isAdmin);
        }

        private void ShowPendingLoansForm()
        {
            if (ExistsPendingLoans())
            {
                PendingLoansForm pendingLoansForm = new PendingLoansForm();
                pendingLoansForm.ShowDialog();
            }
        }

        private bool ExistsPendingLoans()
        {
            using (var db = new MovieCollectionConteiner())
            {
                foreach (Loan loan in db.Loans)
                {
                    if (loan.ReturnDate.CompareTo(DateTime.Now) == -1)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        private void CreateMainForm()
        {
            if (mainForm == null)
                mainForm = new MainForm(this);
            mainForm.FormClosed += new FormClosedEventHandler(mainForm_FormClosed);
            mainForm.Show();
        }

        private void LoginForm_Load(object sender, EventArgs e)
        {
            try
            {
                using (var db = new MovieCollectionConteiner())
                {
                    List<User> users = db.Users.ToList();
                    if (users.Count == 0)
                    {
                        MessageBox.Show("Nenhum usuário cadastrado!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        CreateUserForm createUserForm = new CreateUserForm();
                        createUserForm.buttonBack.Enabled = false;
                        createUserForm.checkBoxAdmin.Checked = true;
                        createUserForm.checkBoxAdmin.Enabled = false;
                        createUserForm.ShowDialog();
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Base de dados não existe. Crie antes de executar!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                buttonGuest.Enabled = false;
            }
        }

        private void mainForm_FormClosed(object sender, EventArgs e)
        {
            Close();
        }

        private void buttonGuest_Click(object sender, EventArgs e)
        {
            Hide();
            CreateMainForm();
            AccessControlsVisibility(false);
        }

        private void AccessControlsVisibility(bool visibility)
        {
            mainForm.buttonAddMovie.Enabled = visibility;
            mainForm.buttonEditMovie.Enabled = visibility;
            mainForm.buttonRemoveMovie.Enabled = visibility;
            mainForm.buttonLendMovie.Enabled = visibility;
            mainForm.menuToolStripMenuItem.Enabled = visibility;
            mainForm.usersToolStripMenuItem.Enabled = visibility;
        }

        private void AdminControlsVisibility(bool isAdmin)
        {
            mainForm.usersToolStripMenuItem.DropDownItems[0].Visible = isAdmin;
            mainForm.usersToolStripMenuItem.DropDownItems[1].Visible = isAdmin;
        }
    }
}
